<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="客户名称" prop="purchaserName">
        <el-input v-model="queryParams.purchaserName" placeholder="请输入客户名称" clearable
          style="width: 240px" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="登录账号" prop="username">
        <el-input v-model="queryParams.username" placeholder="请输入登录账号" clearable
          style="width: 240px" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="客户编号" prop="businessCode">
        <el-input v-model="queryParams.businessCode" placeholder="请输入客户编号" clearable
          style="width: 240px" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="客户类型" prop="mold">
        <el-select v-model="queryParams.mold" placeholder="客户类型" clearable style="width: 240px">
          <el-option v-for="dict in dict.type.purchaser_certified_mold" :key="dict.value"
            :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="账号状态" prop="disabled">
        <el-select v-model="queryParams.disabled" placeholder="账号状态" clearable
          style="width: 240px">
          <el-option label="启用" :value="true" />
          <el-option label="禁用" :value="false" />
        </el-select>
      </el-form-item>
      <el-form-item label="审核状态" prop="applyStatus">
        <el-select v-model="queryParams.applyStatus" placeholder="资质审核状态" clearable
          style="width: 240px">
          <el-option v-for="dict in dict.type.purchaser_apply_status" :key="dict.value"
            :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="省" prop="province">
        <el-select v-model="queryParams.province" clearable @change="provinceChange">
          <el-option v-for="dict in provinceList" :key="dict.value" :label="dict.name" :value="dict.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="市" prop="city">
        <el-select v-model="queryParams.city" clearable @change="cityChange">
          <el-option v-for="dict in cityList" :key="dict.value" :label="dict.name" :value="dict.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="区/县" prop="county">
        <el-select v-model="queryParams.county" clearable>
          <el-option v-for="dict in countyList" :key="dict.value" :label="dict.name" :value="dict.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker v-model="dateRange" style="width: 240px" value-format="yyyy-MM-dd"
          type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" clearable>
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!--
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini"
          @click="handleEditTable(undefined)" v-hasPermi="['system:role:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single"
          @click="handleEditTable" v-hasPermi="['system:role:edit']">修改</el-button>
      </el-col>
      -->
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single"
          @click="temporaryPassage" v-hasPermi="['purchaser:purchaser:applyStatus:edit']">临时通过</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['purchaser:purchaser:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <!-- :disabled="!synchronizeOrders" -->
        <el-button type="primary" plain icon="el-icon-grape" size="mini"
          @click="handleSynchronizePurchasers"
          v-hasPermi="['purchaser:purchaser:sync']">同步数据</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns">
      </right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="purchaserList" border
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column :label="columns[0].label" :prop="columns[0].prop"
        :show-overflow-tooltip="true" :width="columns[0].width" v-if="columns[0].visible" />
      <el-table-column :label="columns[1].label" :prop="columns[1].prop"
        :show-overflow-tooltip="true" :width="columns[1].width" v-if="columns[1].visible" />
      <el-table-column :label="columns[2].label" :prop="columns[2].prop"
        :show-overflow-tooltip="true" :width="columns[2].width" v-if="columns[2].visible" />
      <el-table-column :label="columns[3].label" :prop="columns[3].prop"
        :show-overflow-tooltip="true" :width="columns[3].width" v-if="columns[3].visible" />
      <el-table-column :label="columns[4].label" :prop="columns[4].prop"
        :show-overflow-tooltip="true" :width="columns[4].width" v-if="columns[4].visible" />
      <el-table-column :label="columns[5].label" :prop="columns[5].prop"
        :show-overflow-tooltip="true" :width="columns[5].width" v-if="columns[5].visible" />
      <el-table-column :label="columns[6].label" :prop="columns[6].prop"
        :show-overflow-tooltip="true" :width="columns[6].width" v-if="columns[6].visible" />
      <el-table-column :label="columns[7].label" :prop="columns[7].prop" align="center"
        :show-overflow-tooltip="true" :width="columns[7].width" v-if="columns[7].visible">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.disabled" @change="handleDisabledChange(scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column :label="columns[8].label" :prop="columns[8].prop" align="center"
        :width="columns[8].width" v-if="columns[8].visible">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.purchaser_certified_mold" :value="scope.row.mold" />
        </template>
      </el-table-column>
      <el-table-column :label="columns[9].label" :prop="columns[9].prop" align="center"
        :width="columns[9].width" v-if="columns[9].visible">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.purchaser_apply_status" :value="scope.row.applyStatus" />
        </template>
      </el-table-column>
      <el-table-column :label="columns[10].label" :prop="columns[10].prop"
        :show-overflow-tooltip="true" :width="columns[10].width" v-if="columns[10].visible" />
      <el-table-column :label="columns[11].label" :prop="columns[11].prop"
        :show-overflow-tooltip="true" :width="columns[11].width" v-if="columns[11].visible" />
      <el-table-column :label="columns[12].label" :prop="columns[12].prop"
        :show-overflow-tooltip="true" :width="columns[12].width" v-if="columns[12].visible" />
      <el-table-column :label="columns[13].label" :prop="columns[13].prop"
        :show-overflow-tooltip="true" :width="columns[13].width" v-if="columns[13].visible" />
      <el-table-column :label="columns[14].label" align="center" :prop="columns[14].prop"
        :width="columns[14].width" v-if="columns[14].visible">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="columns[15].label" align="center" :prop="columns[15].prop"
        :width="columns[15].width" v-if="columns[15].visible">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.lastLoginDate) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="columns[16].label" :prop="columns[16].prop"
        :show-overflow-tooltip="true" :width="columns[16].width" v-if="columns[16].visible" />
      <el-table-column label="操作" width="140" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-circle-check" @click="openAddressView(scope.row)"
            v-hasPermi="['purchaser:address:list']">收货地址</el-button>
          <!--
          <el-button @click="seeCertificate(scope.row)" size="small">查看证书</el-button>
          <el-button @click="handleEditTable(scope.row)" size="small">登录管理</el-button>
          <el-button @click="openAddRelevanceView(scope.row)" size="small">账号关联</el-button>
          -->
          <!-- <el-button @click="examineDetailsClick(scope.row)" size="small">审核详情</el-button> -->

          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)"
            v-hasPermi="['purchaser:purchaser:business:edit', 'purchaser:purchaser:certified:material:list', 'purchaser:purchaser:member:edit', 'purchaser:purchaser:relevance:edit']">
            <span class="el-dropdown-link">
              <i class="el-icon-d-arrow-right el-icon--right"></i>更多
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="openBusinessContent" icon="el-icon-circle-check"
                v-hasPermi="['purchaser:purchaser:business:edit']">经营范围</el-dropdown-item>
              <el-dropdown-item command="openSeeCertificate" icon="el-icon-circle-check"
                v-hasPermi="['purchaser:purchaser:certified:material:list']">查看资质</el-dropdown-item>
              <el-dropdown-item command="openHandleEditTable" icon="el-icon-grape"
                v-hasPermi="['purchaser:purchaser:member:edit']">登录管理</el-dropdown-item>
              <el-dropdown-item command="handleTemporaryPwd" icon="el-icon-grape"
                v-hasPermi="['purchaser:member:temporaryPwd']">临时密码</el-dropdown-item>
              <el-dropdown-item command="openAddRelevanceView" icon="el-icon-delete"
                v-hasPermi="['purchaser:purchaser:relevance:edit']">账号关联</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 打开临时密码对话框 -->
    <el-dialog v-dialogDragWidth v-dialogDragHeight v-dialogDrag title="临时登录密码"
      :visible.sync="openTemporaryPwdFlag" width="450px" append-to-body>
      <el-form ref="temporaryPwdForm" label-width="80px">
        <el-row>
          <el-col>
            <el-form-item label="登录账号" prop="username">
              <el-input v-model="currentRow.username" style="width:215px;margin-right:10px" readonly></el-input>
              <el-button id="copyUsername">复 制</el-button>
            </el-form-item>
            <el-form-item label="临时密码" prop="tmpPwd">
              <el-input v-model="temporaryPwd" style="width:130px;margin-right:10px" readonly></el-input>
              <el-button @click="refreshTemporaryPwd" v-hasPermi="['purchaser:member:temporaryPwd']">刷 新</el-button>
              <el-button id="copyTmpPwd">复 制</el-button>
            </el-form-item>
            <p style="color: orangered;">临时密码一分钟内有效</p>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>

    <!-- 查看 证书 -->
    <el-dialog v-dialogDragWidth v-dialogDragHeight v-dialogDrag
      :visible.sync="seeCertificateVisible" width="35%">
      <el-table :data="seeCertificateList" border>
        <el-table-column prop="classificationName" label="证书名称" align="center"> </el-table-column>
        <el-table-column prop="expireTime" label="过期时间" align="center">
          <template slot-scope='scope'>
            {{ parseTime(scope.row.expireTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作项" align="center" width="150">
          <template slot-scope="scope">
            <el-button v-hasPermi="['purchaser:purchaser:certified:material:remove']" @click="delEnterpriseImg(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 经营范围 -->
    <el-dialog v-dialogDragWidth v-dialogDragHeight v-dialogDrag
      :visible.sync="businessRangeVisible" width="500px">
      <el-input type="textarea" ref="businessRange" autosize resize v-model="businessRange"> </el-input>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="clickBusiness">修 改</el-button>
        <el-button @click="businessRangeVisible = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 编辑登录账号 -->
    <el-dialog v-dialogDragWidth v-dialogDragHeight v-dialogDrag
      :visible.sync="businessRangeVisible2" width="600px">
      <el-form :inline="true" label-width="100px">
        <el-card shadow="always">
          <el-form-item label="修改密码：">
            <el-input v-model="modifyPassword" style="width:250px;margin-right:10px"></el-input>
          </el-form-item>
          <el-button type="primary" @click="clickBusiness2">修 改</el-button>
        </el-card>
        <el-card shadow="always">
          <el-form-item label="修改账号：">
            <el-input v-model="modifyAccount" style="width:250px;margin-right:10px"></el-input>
          </el-form-item>
          <!--
          <el-form-item label="修改手机号：">
            <el-input v-model="modifyPhone" style="width:250px;margin-right:10px"></el-input>
          </el-form-item>
          -->
          <el-form-item label="采购员：">
            <el-input v-model="buyerName" style="width:250px;margin-right:10px"></el-input>
          </el-form-item>
          <el-button type="primary" @click="clickBusiness3">修 改</el-button>
        </el-card>
      </el-form>
    </el-dialog>

    <!-- 客户关联 -->
    <el-dialog v-dialogDragWidth v-dialogDragHeight v-dialogDrag :visible.sync="relevanceVisible"
      width="500px">
      <el-input type="textarea" autosize resize v-model="relevanceBusinessCodes"> </el-input>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleAddRelevance">关联</el-button>
        <el-button @click="relevanceVisible = false">取消</el-button>
      </div>
    </el-dialog>

    <!-- 查看 收货地址 -->
    <el-dialog v-dialogDragWidth v-dialogDragHeight v-dialogDrag
      :visible.sync="addressViewVisible" width="80%">
      <el-table :data="addressList" border>
        <el-table-column prop="province" label="省" :show-overflow-tooltip="true" align="center"> </el-table-column>
        <el-table-column prop="city" label="市" :show-overflow-tooltip="true" align="center"> </el-table-column>
        <el-table-column prop="county" label="区/县" :show-overflow-tooltip="true" align="center"> </el-table-column>
        <el-table-column prop="detail" label="详细地址" :show-overflow-tooltip="true" align="center"> </el-table-column>
        <el-table-column prop="name" label="收货人" :show-overflow-tooltip="true" align="center"> </el-table-column>
        <el-table-column prop="mobile" label="联系电话" :show-overflow-tooltip="true" align="center"> </el-table-column>
        <el-table-column prop="erpAddressId" label="ERP编号" :show-overflow-tooltip="true" align="center"></el-table-column>
        <el-table-column prop="createTime" label="同步时间" :show-overflow-tooltip="true" align="center"></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addressViewVisible = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getRegionList } from "@/api/region"
import {
  list, getPurchaserImgLabel, deletePurchaserQualifications, updateBusiness,
  changePassword, changeAccount, changePhone, examinePurchaser, deletePurchasercertifiedMaterial,
  addRelevance,
  getAddressList
} from "@/api/purchaser/purchaser";
import {updateDisabled, refreshTmpPwd} from "@/api/purchaser/member";
import ClipboardJS from 'clipboard'

export default {
  name: "PurchaserSellList",
  dicts: ["purchaser_certified_mold", "purchaser_apply_status"],
  data () {
    return {
      // 遮罩层
      loading: true,
      openTemporaryPwdFlag: false,
      temporaryPwd: undefined,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      regionList: [],
      provinceList: [],
      cityList: [],
      countyList: [],
      // 客户表格数据
      purchaserList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      // 日期范围
      dateRange: [],
      // 列信息
      columns: [
        { key: 0, label: `客户名称`, prop: "purchaserName", width: 260, visible: true },
        { key: 1, label: `法人姓名`, prop: "legalPersonName", width: 90, visible: false },
        { key: 2, label: `客户编号`, prop: "businessCode", width: 90, visible: true },
        { key: 3, label: `采购员`, prop: "memberName", width: 80, visible: true },
        { key: 4, label: `电话`, prop: "mobile", width: 120, visible: true },
        { key: 5, label: `客户内码`, prop: "code", width: 120, visible: false },
        { key: 6, label: `登录账号`, prop: "username", width: 120, visible: true },
        { key: 7, label: `账号状态`, prop: "disabled", width: 80, visible: true },
        { key: 8, label: `客户类型`, prop: "mold", width: 100, visible: true, },
        { key: 9, label: `审核状态`, prop: "applyStatus", width: 100, visible: true },
        { key: 10, label: `客户ID`, prop: "purchaserId", width: 180, visible: false },
        { key: 11, label: `账号ID`, prop: "memberId", width: 180, visible: false },
        { key: 12, label: `经营范围`, prop: "business", width: 450, visible: true },
        { key: 13, label: `纳税人识别号`, prop: "taxpayerNo", width: 170, visible: false },
        { key: 14, label: `创建时间`, prop: "createTime", width: 160, visible: false },
        { key: 15, label: `最后登录时间`, prop: "lastLoginDate", width: 160, visible: false },
        { key: 16, label: `客户联系电话`, prop: "contactMobile", width: 120, visible: false },
      ],
      // 当前行数据
      currentRow: {
        username: ''
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        purchaserName: '',
        username: '',
        businessCode: '',
        mold: '',
        disabled: undefined,
        applyStatus: '',
        paramMap: { applyStatus: 'EXPIRE,PASS' },
      },

      // 表单参数
      form: {},
      // 表单校验
      rules: {
        promotionPrice: [
          { required: true, message: "促销价格不能为空", trigger: "blur" }
        ],
        roleKey: [
          { required: true, message: "权限字符不能为空", trigger: "blur" }
        ],
        roleSort: [
          { required: true, message: "角色顺序不能为空", trigger: "blur" }
        ]
      },
      // 查看证书 状态
      seeCertificateVisible: false,
      // 查看证书 列表
      seeCertificateList: [],
      // 经营范围
      businessRange: '',
      modifyPassword: '',
      modifyAccount: '',
      modifyPhone: '',
      buyerName: '',
      businessRangeVisible: false,
      businessRangeVisible2: false,
      purchaserId: '',
      memberId: '',

      relevanceVisible: false,
      relevanceId: undefined,
      relevanceBusinessCodes: '',

      addressList: [],
      addressViewVisible: false,
    };
  },
  created () {
    this.handleRegionList()
    this.getList();
  },
  mounted() {
    const usernameClipboard = new ClipboardJS('#copyUsername', {
      text: trigger => {
        this.$notify({
          title: '成功',
          message: '登录账号已复制到剪切板，可粘贴。',
          type: 'success'
        })
        return this.currentRow.username
      }
    })
    usernameClipboard.on('error', e => {
      this.$message.error('登录账号复制失败')
    })

    const tmpPwdClipboard = new ClipboardJS('#copyTmpPwd', {
      text: trigger => {
        this.$notify({
          title: '成功',
          message: '临时密码已复制到剪切板，可粘贴。',
          type: 'success'
        })
        return this.temporaryPwd
      }
    })
    tmpPwdClipboard.on('error', e => {
      this.$message.error('临时密码复制失败')
    })
  },
  methods: {
    handleRegionList(){
      getRegionList().then(res=>{
        res.data.forEach(region=>{
          if('province' === region.level){
            this.provinceList.push({id: region.id, name: region.name})
          } else{
            this.regionList.push({id: region.id, name: region.name, parentId: region.parentId, level: region.level})
          }
        })
        this.provinceList.sort(region.orderNum)
        this.regionList.sort(region.orderNum)
      })
    },
    provinceChange(){
      this.cityList = []
      this.regionList.forEach(region=>{
        if('city' === region.level){
          if(region.parentId == this.queryParams.province){
            this.cityList.push(region)
          }
        }
      })
    },
    cityChange(){
      this.countyList = []
      this.regionList.forEach(region=>{
        if('district' === region.level){
          if(region.parentId == this.queryParams.city){
            this.countyList.push(region)
          }
        }
      })
    },
    /** 查询客户列表 */
    getList () {
      this.loading = true;
      this.queryParams.purchaserName = this.queryParams.purchaserName.trim()
      this.queryParams.username = this.queryParams.username.trim()
      this.queryParams.businessCode = this.queryParams.businessCode.trim().toUpperCase()
      list(this.addDateRangeWithMap(this.queryParams, this.dateRange, "CreateTime")).then(response => {
        this.purchaserList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    // 经营范围
    businessContent (row) {
      this.businessRangeVisible = true
      this.businessRange = row.business
      this.purchaserId = row.purchaserId
    },

    //  修改经营范围
    clickBusiness () {
      let that = this
      this.$modal.confirm('确认修改吗？').then(function () {
        return updateBusiness(that.purchaserId, { business: that.businessRange })
      }).then(() => {
        this.businessRangeVisible = false
        this.$modal.msgSuccess("成功")
        this.getList()
      })

      // updateBusiness(this.purchaserId, { business: this.businessRange }).then(res => {
      //   if (res.code === 200) {
      //     console.log(res)
      //   }
      // })
    },

    clickBusiness2 () {
      let that = this
      this.$modal.confirm('确认修改吗？').then(function () {
        return changePassword(that.purchaserId, that.memberId, { password: that.modifyPassword })
      }).then(() => {
        this.$modal.msgSuccess("成功")
        this.businessRangeVisible2 = false
      })
    },
    clickBusiness3 () {
      let that = this
      this.$modal.confirm('确认修改吗？').then(function () {
        return changeAccount(that.purchaserId, { username: that.modifyAccount, mobile: that.modifyAccount, name: that.buyerName })
        .then(res=>{
          that.getList()
        })
      }).then(() => {
        this.$modal.msgSuccess("成功")
        this.businessRangeVisible2 = false
      })
    },

    // 删除证书
    delEnterpriseImg (row) {
      let _this = this
      this.$modal.confirm('确认删除<' + row.classificationName + '>吗？').then(function () {
        deletePurchasercertifiedMaterial(row.purchaserId, row.id).then(res=>{
          _this.$modal.msgSuccess("成功")
          _this.seeCertificate({purchaserId: row.purchaserId})
        })
      }).catch(()=>{
        console.log("取消删除资质")
      })
    },
    // 查看证书
    seeCertificate (row) {
      getPurchaserImgLabel(row.purchaserId).then(res => {
        if (res.code === 200) {
          this.seeCertificateList = res.data
          this.seeCertificateVisible = true
          // res.data.forEach(k => {
          //   const a = new Date(k.expireTime)
          //   let dates = a.getFullYear() + '-' + (a.getMonth() + 1) + '-' + a.getDate() + " " + a.getHours() + ':' + a.getMinutes() + ':' + a.getSeconds()
          //   this.$set(k, 'dates', dates)
          //   this.seeCertificateList.push(k)
          // })
        }
      })
    },
    //刷新临时密码
    refreshTemporaryPwd () {
      refreshTmpPwd(this.currentRow.memberId).then(res=>{
        this.temporaryPwd = res.data
      })
    },
    // 促销状态修改
    handlePromotionStatusChange (row, promotionPrice) {
      let text = row.promotionFlag === true ? "促销" : "取消促销";
      this.$modal.confirm('确认"' + text + '""' + row.goodsName + '"商品吗？').then(function () {
        return changeGoodsSkuPromotionFlag(
          row.goodsId,
          row.id,
          row.promotionFlag,
          promotionPrice
        )
      }).then(() => {
        this.openTemporaryPwdFlag = false;
        row.promotionPrice = promotionPrice;

        this.$modal.msgSuccess(text + "成功");
      }).catch(function () {
        console.log("出错了");
        row.promotionFlag = !row.promotionFlag;
      })
    },
    // 推荐状态修改
    handleRecommendStatusChange (row) {
      let text = row.recommend === true ? "推荐" : "取消推荐";
      this.$modal.confirm('确认"' + text + '""' + row.goodsName + '"商品吗？').then(function () {
        return changeGoodsSkuRecommend(row.goodsId, row.id, row.recommend);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function () {
        row.recommend = !row.recommend;
      })
    },
    // 应季状态修改
    handleSeasonalStatusChange (row) {
      let text = row.seasonal === true ? "应季热销" : "取消应季热销";
      this.$modal.confirm('确认"' + text + '""' + row.goodsName + '"商品吗？').then(function () {
        return changeGoodsSkuSeasonal(row.goodsId, row.id, row.seasonal);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function () {
        row.seasonal = !row.seasonal;
      })
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset () {
      this.form = {
        point: 0,
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery () {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map(item => item.purchaserId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 修改密码/登录账号 操作 */
    handleEditTable (row) {
      // const params = { pageNum: 1 };
      // if (row) {
      //   params.goodsSku = {
      //     id: row.id,
      //     goodsId: row.goodsId,
      //     goodsName: row.goodsName
      //   };
      // }
      // const tabTitle = row ? "修改商品" : "新增商品";
      // this.$tab.openPage(tabTitle, "/goods", params);

      this.modifyPassword = ''
      this.modifyAccount = ''
      this.modifyPhone = ''
      this.buyerName = ''

      this.memberId = row.memberId
      this.purchaserId = row.purchaserId
      this.businessRange2 = ''
      this.businessRangeVisible2 = true
    },
    /** 导出按钮操作 */
    handleExport () {
      this.download(
        "purchaser/purchaser/export",
        {
          ...this.queryParams
        },
        `客户列表_${this.parseTime(new Date().getTime(), "{y}-{m}-{d}_{h}:{i}:{s}")}.xlsx`
      );
    },
    handleSynchronizePurchasers () {
      //window.open('http://www.xdyy365.com:5003/wholesale/sync-api/order/check', '_black')
      window.open('http://www.xdyy365.com:5003/wholesale/sync-api/sync/purchaser', '_black')
      // axios({ method: 'get', url: 'http://www.xdyy365.com:5003/wholesale/sync-api/order/refresh', }).then(res => {
      //   console.log(res)
      // })
    },
    temporaryPassage () {
      let purchaserId = this.ids[0];
      const _this = this
      this.$modal.confirm('确认将此客户审核状态修改为通过吗？').then(function () {
        examinePurchaser(purchaserId, { applyStatus: 'PASS' }).then(res => {
          _this.purchaserList.forEach(item => {
            if (purchaserId == item.purchaserId) {
              item.applyStatus = 'PASS'
            }
          });

          _this.$modal.msgSuccess("成功")
        });
      });
    },
    openAddRelevanceView (purchaser) {
      this.relevanceId = purchaser.purchaserId
      if (purchaser.relevanceId) {
        this.relevanceId = purchaser.relevanceId;
      }
      this.relevanceBusinessCodes = purchaser.businessCode;

      list({ relevanceId: this.relevanceId, pageSize: 10000 }).then(response => {
        if(response.rows.length > 0){
          this.relevanceBusinessCodes = "";
          for (let i = 0; i < response.rows.length; i++) {
            let item = response.rows[i]

            this.relevanceBusinessCodes += item.businessCode
            if (i < response.rows.length - 1) {
              this.relevanceBusinessCodes += ','
            }
          }
        }
        this.relevanceBusinessCodes += ','

        this.relevanceVisible = true;
      });
    },
    handleAddRelevance () {
      this.relevanceVisible = false;

      let data = new Array();
      this.relevanceBusinessCodes.split(",").forEach(item => {
        item.trim().split("，").forEach(businessCode => {
          data.push(businessCode)
        })
      })

      let _this = this
      this.$modal.confirm('确认关联客户账号吗？').then(function () {
        addRelevance(_this.relevanceId, data).then(res => {
          _this.$modal.msgSuccess("关联成功")
          _this.getList()
        })
      });
    },
    handleDisabledChange(row){
      let text = row.disabled? "启用" : "禁用";
      this.$modal.confirm('确认"' + text + '""' + row.username + '"账号吗？')
        .then(function () {
          return updateDisabled(
            row.memberId,
            row.disabled
          );
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.disabled = !row.disabled;
        });
    },
    // 更多操作触发
    handleCommand (command, row) {
      switch (command) {
        case "openBusinessContent":
          this.businessContent(row);
          break;
        case "openSeeCertificate":
          this.seeCertificate(row);
          break;
        case "openHandleEditTable":
          this.handleEditTable(row);
          break;
        case "handleTemporaryPwd":
          this.openTemporaryPwdView(row);
          break;
        case "openAddRelevanceView":
          this.openAddRelevanceView(row);
          break;
        default:
          break;
      }
    },
    openTemporaryPwdView(row){
      this.currentRow = row
      this.openTemporaryPwdFlag = true
      this.refreshTemporaryPwd()
    },
    openAddressView(row){
      this.loading = true;
      getAddressList({purchaserId: row.purchaserId}).then(response => {
        this.addressList = response.rows;
        console.log(this.addressList)
        this.addressViewVisible = true;
        this.loading = false;
      });
    },
  }
};
</script>
